//
//  DDGScollViewShot.swift
//  DDGScreenshot
//
//  Created by dudongge on 2018/3/19.
//  Copyright © 2018年 dudongge. All rights reserved.
//

import UIKit
import SVProgressHUD
import TZImagePickerController
//import RxSwift
//import RxCocoa

let height = UIScreen.main.bounds.size.height
let width = UIScreen.main.bounds.size.width

class DDGScollViewShot: LCViewController,TZImagePickerControllerDelegate
{
    

    var testScrollView: UIScrollView!
    var storeScrollView: UIScrollView!
    var storeImage: UIImageView! //保存截取的图片
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "制作经文卡片"
        self.setupUI()
    }
    
    
    func setupUI() {
        edgesForExtendedLayout = UIRectEdge.init(rawValue: 0);
        tabBarController?.tabBar.isTranslucent = false;
        testScrollView = UIScrollView()
//        testScrollView.contentSize = CGSize(width: width, height: height)
        testScrollView.frame = CGRect(x: 10, y: 100-64, width: width - 20, height: height - 200)
        testScrollView.backgroundColor = UIColor.white
        self.view.addSubview(testScrollView)
        
        let logoView = UIImageView()
        logoView.image = UIImage(named: "gdt_splash_logo")
        logoView.backgroundColor = view.backgroundColor
        testScrollView.addSubview(logoView)
        
        let imageView0 = UIImageView()
        storeImage = imageView0
        imageView0.image = UIImage(named:"devotion_bannerC")
        testScrollView.addSubview(imageView0)
        imageView0.sizeToFit()

        let cameraButton = UIButton()
        cameraButton.setBackgroundImage(UIImage(named:"拍照")?.lcImage(withTintColor: UIColor.white), for: .normal)
        view.addSubview(cameraButton)
        cameraButton.sizeToFit()
        testScrollView.addSubview(bibleCardTopView)
        // 设置圆角大小
        cameraButton.layer.cornerRadius = cameraButton.height / 2;
        cameraButton.layer.masksToBounds = true;
        cameraButton.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.45)
        cameraButton.alpha = 0.65
        cameraButton.addTarget(self, action: #selector(pushImagePickerVc), for: .touchUpInside)
//        cameraButton.rx.tap
//            .subscribe(onNext: { [weak self] _ in
//                self?.pushImagePickerVc()
//            })
//            .disposed(by: disposeBag)

        let qrcodeImageView = UIImageView()
        qrcodeImageView.image = UIImage.qrImage(for: "http://www.9ku.com/down/fuyin/pc/", imageSize: 180, logoImageSize: 180*0.2)
//        // 保存至相册
//        UIImageWriteToSavedPhotosAlbum(qrcodeImageView.image!, nil, nil, nil);
//        qrcodeImageView.image = UIImage(named:"下载APP二维码")/**?.lcImage(withTintColor: UIColor.lightGray)*/
//        qrcodeImageView.frame = CGRect(x: 10, y: height * 2.0, width: 40, height: 40)
        testScrollView.addSubview(qrcodeImageView)
        let qrcodeBtn = UIButton()
        qrcodeBtn.setTitle("长按扫码\n赞美主耶稣", for: .normal)
        qrcodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        qrcodeBtn.titleLabel?.numberOfLines = 0
        qrcodeBtn.setTitleColor(UIColor(red:0.67, green:0.67, blue:0.67, alpha:1.00), for: .normal)
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 5
        let content = qrcodeBtn.titleLabel!.text!
        let attString = NSMutableAttributedString(string: content)
        attString.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, content.count))
        qrcodeBtn.setAttributedTitle(attString, for: .normal)
        testScrollView.addSubview(qrcodeBtn)
        
        let shareBtn = UIButton()
        shareBtn.backgroundColor = UIColor.white
        shareBtn.setTitle("分享", for: .normal)
        shareBtn.setTitleColor(UIColor.black, for: .normal)
        shareBtn.addTarget(self, action: #selector(DDGScollViewShot.screenShotScroll), for: .touchUpInside)
//        leftBtn.frame = CGRect(x: 20, y: height - 45 - 64 - 40, width: 150, height: 40)
        self.view.addSubview(shareBtn)
        
        let formatView = UIView()//版式
        formatView.backgroundColor = UIColor.white
        view.addSubview(formatView)
        let dashedLine:UIImageView = UIImageView(frame: CGRect(x: 0, y: 250, width: self.view.frame.width, height: 10))
        self.testScrollView.addSubview(dashedLine)

        allViewDidLayoutStyle00(dashedLine,formatView, shareBtn,logoView , imageView0, cameraButton, qrcodeImageView, qrcodeBtn)

        self.view.layoutIfNeeded()
        
        print(qrcodeImageView.frame.maxY+30)
        self.testScrollView.contentSize = CGSize(width: self.testScrollView.width, height: qrcodeImageView.frame.maxY+30)
        
//        //监听版式通知
//        _ = NotificationCenter.default.rx
//            .notification(Notification.Name(rawValue: "DDGScollViewShotDidSelectedItemImageNotification"))
//            .takeUntil(self.rx.deallocated) //页面销毁自动移除通知监听
//            .subscribe(onNext: { [weak self] notification in    //获取通知数据
//                let userInfo = notification.userInfo as! [String: AnyObject]
//                let didSelectIndex = userInfo["didSelectIndex"] as! Int
//                
//                if 3 == didSelectIndex {
//                    self?.allViewDidLayoutStyle04(dashedLine, formatView, shareBtn, imageView0, cameraButton, qrcodeImageView, qrcodeBtn)
//                }
//                if 2 == didSelectIndex {
//                }
//                if 1 == didSelectIndex {
//                }
//                if 0 == didSelectIndex {
//                }
//            })
    }
    
    fileprivate func allViewDidLayoutStyle00(_ dashedLine: UIImageView, _ formatView: UIView ,_ shareBtn: UIButton,_ logoView:UIImageView, _ imageView0: UIImageView, _ cameraButton: UIButton, _ qrcodeImageView: UIImageView, _ qrcodeBtn: UIButton) {
        
        UIGraphicsBeginImageContext(dashedLine.frame.size) // 位图上下文绘制区域
        dashedLine.image?.draw(in: dashedLine.bounds)
        
        let context:CGContext = UIGraphicsGetCurrentContext()!
        
        context.setLineCap(CGLineCap.square)
        //设置虚线排列的宽度间隔:下面的arr中的数字表示先绘制3个点再绘制1个点
        let lengths:[CGFloat] = [10] // 绘制 跳过 无限循环
        //设置虚线颜色
        context.setStrokeColor(UIColor(red:0.67, green:0.67, blue:0.67, alpha:0.80).cgColor)
        //设置虚线宽度
        context.setLineWidth(0.5)
        context.setLineDash(phase: 0, lengths: lengths)
        //设置虚线绘制起点
        context.move(to: CGPoint(x: -46, y: 5))
        context.addLine(to: CGPoint(x: self.view.frame.width, y: 5))
        context.strokePath()
        
        dashedLine.image = UIGraphicsGetImageFromCurrentImageContext()
        dashedLine.snp.makeConstraints { (make) in
            make.bottom.equalTo(qrcodeBtn.snp.top).offset(-30)
            make.left.right.equalTo(self.testScrollView)
            make.height.equalTo(10)
        }
        
        let topBGView = UIView()
        topBGView.backgroundColor = view.backgroundColor
        view.addSubview(topBGView)
        topBGView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.height.equalTo(10)
        }
        testScrollView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.right.equalTo(self.view).offset(-10)
            make.top.equalTo(self.view).offset(10)
            make.bottom.equalTo(formatView.snp.top).offset(-10)
        }
        logoView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.top.equalTo(self.testScrollView).offset(0)
            make.right.equalTo(self.view).offset(-10)
            make.height.equalTo(100)
        }
        imageView0.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.top.equalTo(logoView.snp.bottom).offset(0)
            make.right.equalTo(self.view).offset(-10)
            make.height.equalTo(imageView0.snp.width).dividedBy(imageView0.width/imageView0.height)
        }
        cameraButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(imageView0).offset(-20)
            make.right.equalTo(imageView0).offset(-20)
            make.height.equalTo(cameraButton.snp.width).dividedBy(cameraButton.width/cameraButton.height)
        }
        bibleCardTopView.snp.makeConstraints { (make) in
            make.top.equalTo(imageView0.snp.bottom).offset(30)
            make.left.equalTo(view.snp.left).offset(30)
            make.right.equalTo(view.snp.right).offset(-30)
            make.bottom.equalTo(bibleCardTopView.titleLabel.snp.bottom).offset(20)
        }
        qrcodeImageView.snp.makeConstraints { (make) in
            make.top.equalTo(bibleCardTopView.snp.bottom).offset(30)
            make.left.equalTo(bibleCardTopView.placeholderLabel.snp.left).offset(0)
            make.width.equalTo(60)
            make.height.equalTo(60)
        }
        qrcodeBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(qrcodeImageView.snp.centerY).offset(0)
            make.left.equalTo(qrcodeImageView.snp.right).offset(10)
        }
        shareBtn.snp.makeConstraints { (make) in
            make.height.equalTo(50)
            make.left.equalTo(view.snp.left).offset(0)
            make.right.equalTo(view.snp.right).offset(0)
            make.bottom.equalTo(view.snp.bottom).offset(-kTabBarHeight+49)
        }
        formatView.snp.makeConstraints { (make) in
            make.height.equalTo(0)//70
            make.left.equalTo(view.snp.left).offset(0)
            make.right.equalTo(view.snp.right).offset(0)
            make.bottom.equalTo(shareBtn.snp.top).offset(-1)
        }
        formatView.isHidden = true//暂时屏蔽掉其他样式
        self.addPagerView(formatView)
        self.pagerView.frame = CGRect(x: 64, y: 0, width: self.view.frame.width-64, height: 70)
        self.setupFormatLabel(formatView)//版式文字
//        self.pagerView.snp.makeConstraints { (make) in
//            make.height.equalTo(0)//70
//            make.left.equalTo(view.snp.left).offset(0)
//            make.right.equalTo(view.snp.right).offset(0)
//            make.bottom.equalTo(shareBtn.snp.top).offset(-1)
//        }
    }
    
    fileprivate func setupFormatLabel(_ formatView: UIView) {
        let formatLabel : UILabel = UILabel()
        formatLabel.text = "版式"
        formatLabel.font = UIFont.systemFont(ofSize: 18)
        formatView.addSubview(formatLabel)
        formatLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo((64+10)/2)
            make.centerY.equalTo(self.pagerView.snp.centerY)
        }
    }
    @objc func pushImagePickerVc() {
        let imagePickerVc: TZImagePickerController
        imagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self)
        imagePickerVc.allowPickingOriginalPhoto = false
        imagePickerVc.allowPickingVideo = false
        imagePickerVc.showSelectBtn = false
        imagePickerVc.allowCrop = true
        // 设置竖屏下的裁剪尺寸
        let left: CGFloat = 0.0
        let widthHeight: CGFloat = self.view.width - 2*left
        let top: CGFloat = (ScreenHeight - widthHeight*(9/16))/2
        imagePickerVc.cropRect = CGRect(x :left, y: top, width: widthHeight, height: widthHeight*(9/16))
        // photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
        imagePickerVc.didFinishPickingPhotosHandle = {[weak self] (photos, assets, isSelectOriginalPhoto) -> Void in
            for image in photos! {
                print(image)
                self?.storeImage.image = image
                //self?.composePictureView.addImage(image: image)//.dealImageScale(maxWidth: 828)
            }
        }
        self.present(imagePickerVc, animated:true, completion:nil);
    }
    ///MARK:- 分享
    ///分享
    @objc func screenShotScroll() {
        weak var ws = self
        self.testScrollView.DDGContentScrollScreenShot { (image) in
            LCUtils.shotBlock(image, success: { (type) in
                if type == 0{
                    ws!.lcShareViewDidSelecteBtn(withBtnText: "分享微信", imageData: image/**?.dealImageScale(maxWidth: 400)*/)
                }else if  type == 1{
                    ws!.lcShareViewDidSelecteBtn(withBtnText: "分享朋友圈", imageData: image)
                }else if type == 2{
                    //分享到圣经金句动态
                    ws!.shotDynamicShare(withType: "6", dataImages: [image ?? UIImage()], success: { (dict) in
                        SVProgressHUD.showSuccess(withStatus: "分享动态成功")
                    }, failure: { (errorString) in
                        SVProgressHUD.showError(withStatus: errorString)
                    })
                }else if type == 3{
                    LCUtils.openOSMore(withWebLink: nil, title: nil, text_image: image)
                }
            }, hidden: {
            })
        }
    }
    deinit {
        print("DDGScollViewShot 已经释放了 deinit")
    }
    @objc var shengJingTitle : String = String();
    @objc var notesContentStr : String = String();
    @objc var selectedData : Array<Any> = Array<Any>();

    //顶部视图
    fileprivate lazy var bibleCardTopView:LCBibleCardTopView = {
        let view = LCBibleCardTopView()
        self.setupComposeTextView(view)//设置
        return view
    }()
    //FIXME:- 下午4:57///设置顶部视图 LCBibleCardTopView
    fileprivate func setupComposeTextView(_ view : LCBibleCardTopView){
//        let familys = UIFont.familyNames
//        for family in familys {
//            print(family)
//            let fonts = UIFont.fontNames(forFamilyName: family)
//            for font in fonts {
//                print(font)
//            }
//        }
//        NSArray *familys = [UIFont familyNames];
//        for (int i =0; i<familys.count; i++) {
//            NSString *family = [familys objectAtIndex:i];
//            NSLog(@"family = %@",family);
//
//            NSArray *fonts = [UIFontfontNamesForFamilyName:family];
//            for (int j =0; j<fonts.count; j++) {
//                NSString *font = [fonts objectAtIndex:j];
//                NSLog(@"font = %@",font);
//            }
//        }
        //FIXME:- // 设置文字内容
        view.placeholderLabel.text = notesContentStr
        view.titleLabel.text = "" + shengJingTitle
        view.placeholderLabel.font = UIFont(name: "KaiTi_GB2312", size: 18)
        view.titleLabel.font = UIFont(name: "KaiTi_GB2312", size: 18)

        //Swift - 设置UILabel、UITextView的文字行间距
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 5
        let content = view.placeholderLabel.text!
        let attString = NSMutableAttributedString(string: content)
        attString.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, content.count))
        view.placeholderLabel.attributedText = attString
        
    }
    
    lazy var datas = [String]()
    
    lazy var pagerView: LCCyclePagerView = {
        let pagerView = LCCyclePagerView()
        pagerView.isInfiniteLoop = false
        return pagerView
    }()
    

}

///MARK:- 版式
extension DDGScollViewShot {
    
    func addPagerView(_ formatView: UIView) {
//        self.pagerView.layer.borderWidth = 1;
        self.pagerView.dataSource = self
        self.pagerView.delegate = self
        self.pagerView.register(DDGScollShotBottomCyclePagerCell.classForCoder(), forCellWithReuseIdentifier: "DDGScollShotBottomCyclePagerCellIdentifier")
        formatView.addSubview(self.pagerView)
        self.loadPagerViewData()
    }
    
    func loadPagerViewData() {
        var i = 0
        while i < 4 {
            self.datas.append("排版图标_0\(i+1)")
            i += 1
        }
        self.pagerView.reloadData()
    }
    
}
extension DDGScollViewShot: LCCyclePagerViewDelegate, LCCyclePagerViewDataSource {
    
    // MARK: LCCyclePagerViewDataSource
    func numberOfItems(in pageView: LCCyclePagerView) -> Int {
        return self.datas.count
    }
    
    func pagerView(_ pagerView: LCCyclePagerView, cellForItemAt index: Int) -> UICollectionViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "DDGScollShotBottomCyclePagerCellIdentifier", for: index) as! DDGScollShotBottomCyclePagerCell
        cell.bgImageView.tag = index
        cell.bgImageView.image = UIImage(named: self.datas[index])
        return cell
    }
    
    func layout(for pageView: LCCyclePagerView) -> LCCyclePagerViewLayout {
        let layout = LCCyclePagerViewLayout()
        layout.itemSize = CGSize(width: 65, height: 44)//
        layout.itemSpacing = 20//间距20
        
        return layout
    }
    func pagerView(_ pageView: LCCyclePagerView, didSelectedItemCell cell: UICollectionViewCell, at index: Int) {
        let notificationName = Notification.Name(rawValue: "DDGScollViewShotDidSelectedItemImageNotification")
        NotificationCenter.default.post(name: notificationName, object: self, userInfo: ["didSelectIndex" : index])
    }
}


extension DDGScollViewShot {
    fileprivate func allViewDidLayoutStyle01(_ dashedLine: UIImageView, _ formatView: UIView ,_ shareBtn: UIButton, _ imageView0: UIImageView, _ cameraButton: UIButton, _ qrcodeImageView: UIImageView, _ qrcodeBtn: UIButton) {
        
        dashedLine.isHidden = false
        bibleCardTopView.lineView.isHidden = true
        //图片
        imageView0.snp.remakeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.top.equalTo(qrcodeImageView.snp.bottom).offset(30)
            make.right.equalTo(self.view).offset(-10)
            make.height.equalTo(imageView0.snp.width).dividedBy(imageView0.width/imageView0.height)
        }
        bibleCardTopView.snp.remakeConstraints { (make) in
            make.top.equalTo(self.testScrollView.snp.top).offset(20)
            make.left.equalTo(view.snp.left).offset(30)
            make.right.equalTo(view.snp.right).offset(-30)
            make.bottom.equalTo(bibleCardTopView.titleLabel.snp.bottom).offset(20)
        }
        //二维码图案
        qrcodeImageView.snp.remakeConstraints { (make) in
            make.top.equalTo(bibleCardTopView.snp.bottom).offset(30)
            make.right.equalTo(bibleCardTopView.placeholderLabel.snp.right).offset(0)
            make.width.equalTo(60)
            make.height.equalTo(60)
        }
        //二维码文字
        qrcodeBtn.snp.remakeConstraints { (make) in
            make.centerY.equalTo(qrcodeImageView.snp.centerY).offset(0)
            make.right.equalTo(qrcodeImageView.snp.left).offset(-10)
        }
        self.view.layoutIfNeeded()
        self.testScrollView.contentSize = CGSize(width: self.testScrollView.width, height: imageView0.frame.maxY)
    }

    fileprivate func allViewDidLayoutStyle04(_ dashedLine: UIImageView, _ formatView: UIView ,_ shareBtn: UIButton, _ imageView0: UIImageView, _ cameraButton: UIButton, _ qrcodeImageView: UIImageView, _ qrcodeBtn: UIButton) {
        dashedLine.isHidden = true
        bibleCardTopView.lineView.isHidden = false
        //图片
        imageView0.snp.remakeConstraints { (make) in
            make.left.equalTo(self.view).offset(10)
            make.top.equalTo(qrcodeImageView.snp.bottom).offset(30)
            make.right.equalTo(self.view).offset(-10)
            make.height.equalTo(imageView0.snp.width).dividedBy(imageView0.width/imageView0.height)
        }
        bibleCardTopView.snp.remakeConstraints { (make) in
            make.top.equalTo(self.testScrollView.snp.top).offset(20)
            make.left.equalTo(view.snp.left).offset(30)
            make.right.equalTo(view.snp.right).offset(-30)
            make.bottom.equalTo(bibleCardTopView.titleLabel.snp.bottom).offset(20)
        }
        //二维码图案
        qrcodeImageView.snp.remakeConstraints { (make) in
            make.top.equalTo(bibleCardTopView.snp.bottom).offset(30)
            make.right.equalTo(bibleCardTopView.placeholderLabel.snp.right).offset(0)
            make.width.equalTo(60)
            make.height.equalTo(60)
        }
        //二维码文字
        qrcodeBtn.snp.remakeConstraints { (make) in
            make.centerY.equalTo(qrcodeImageView.snp.centerY).offset(0)
            make.right.equalTo(qrcodeImageView.snp.left).offset(-10)
        }
        self.view.layoutIfNeeded()
        self.testScrollView.contentSize = CGSize(width: self.testScrollView.width, height: imageView0.frame.maxY)
    }

    
}
